package com.lb.shopguide.ui.fragment.boss;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMapOptions;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.LubanOptions;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.AppConfigManager;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.QiniuInfo;
import com.lb.shopguide.entity.StoreDetailBean;
import com.lb.shopguide.entity.local.AreaBean;
import com.lb.shopguide.event.boss.AddShopEvent;
import com.lb.shopguide.event.boss.AddShopEventInMine;
import com.lb.shopguide.event.boss.EditShopEvent;
import com.lb.shopguide.event.boss.RookieAddShopEvent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.dialog.DialogSelectPic;
import com.lb.shopguide.ui.view.ClearTitleBar;
import com.lb.shopguide.ui.view.LbMapContainer;
import com.lb.shopguide.util.AMapUtil;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.lb.shopguide.util.lb.SelectPicUtil;
import com.lb.shopguide.util.pic.ImageLoaderUtils;
import com.qiniu.android.common.AutoZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * Created by kang on 2017/12/27.
 */

public class FragmentAddEditShop extends BaseCommonFragment implements TakePhoto.TakeResultListener, InvokeListener, GeocodeSearch.OnGeocodeSearchListener {
    @BindView(R.id.ctb)
    ClearTitleBar ctb;
    @BindView(R.id.et_shop_name)
    EditText etShopName;
    @BindView(R.id.et_shop_phone_num)
    EditText etShopPhoneNum;
    @BindView(R.id.et_postal_code)
    EditText etPostalCode;
    @BindView(R.id.et_login_name)
    EditText etLoginName;
    @BindView(R.id.et_login_password)
    EditText etLoginPwd;
    @BindView(R.id.tv_shop_addr)
    TextView tvShopAddr;
    @BindView(R.id.et_exact_addr)
    EditText etExactAddr;
    @BindView(R.id.layout_shop_addr)
    RelativeLayout layoutShopAddr;
    @BindView(R.id.btn_add_shop)
    TextView tvAddShop;
    @BindView(R.id.iv_add_pic)
    ImageView ivAddPic;
    @BindView(R.id.layout_delete_shop)
    RelativeLayout layoutDeletePic;
    @BindView(R.id.iv_shop_logo)
    ImageView ivShopLogo;
    @BindView(R.id.iv_delete_pic)
    ImageView ivDeletePic;
    @BindView(R.id.iv_addr_search)
    ImageView ivAddrSearch;
    @BindView(R.id.map_container)
    LbMapContainer mapContainer;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    private MapView mapView;

    private ArrayList<String> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;

    private String province;
    private String city;
    private String district;
    private boolean isLoaded = false;
    private int mode = -1;

    private AMap aMap;
    private Marker markerLocation;
    private Marker shopMarker;
    private CameraPosition cameraPosition;
    private LatLng shopPosition;
    private int defaultMapLevel = 15;
    private GeocodeSearch geocoderSearch;

    private InvokeParam invokeParam;
    private TakePhoto takePhoto;
    private String filePath;
    private String picUrl;
    private String defaultCity = "上海";
    private StoreDetailBean storeDetailBean;

    private UploadManager uploadManager;
    private int type;//新增门店、编辑门店

    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;


    public static FragmentAddEditShop newInstance() {
        return new FragmentAddEditShop();
    }

    public static FragmentAddEditShop newInstance(int id) {
        FragmentAddEditShop fragmentAddEditShop = new FragmentAddEditShop();
        Bundle bundle = new Bundle();
        bundle.putInt(AppConstant.STORE_ID, id);
        fragmentAddEditShop.setArguments(bundle);
        return fragmentAddEditShop;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_add_shop, container, false);
        unbinder = ButterKnife.bind(this, view);
        mapView = view.findViewById(R.id.mapview);
        if (mapView != null) {
            mapView.onCreate(savedInstanceState);
        }
        initData();
        initView();
        bindMap();

        return view;
    }

    private void bindMap() {
        initMap();
        if (shopMarker == null) {
            MarkerOptions markerOptions = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.iv_shop_address));
            if (shopPosition != null) {
                markerOptions.position(shopPosition).draggable(true);
            }
            shopMarker = aMap.addMarker(markerOptions);
        }
        if (getCameraPosition() == null) {
            aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(shopPosition, defaultMapLevel, 0, 0)));
        } else {
            aMap.moveCamera(CameraUpdateFactory.newCameraPosition(getCameraPosition()));
        }
    }

    private void initMap() {
        aMap = mapView.getMap();
        aMap.getUiSettings().setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_CENTER);
        aMap.getUiSettings().setMyLocationButtonEnabled(false); // 是否显示默认的定位按钮
        aMap.setMyLocationEnabled(false);// 是否可触发定位并显示定位层
        aMap.getUiSettings().setZoomControlsEnabled(false);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_add_shop;
    }

    @Override
    public void initData() {
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.STORE_ID)) {
            type = AppConstant.STATE_EDIT_SHOP;
            sendRequestGetStoreById(bundle.getInt(AppConstant.STORE_ID));
        } else {
            type = AppConstant.STATE_ADD_SHOP;
        }
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        Configuration config = new Configuration.Builder().zone(AutoZone.autoZone).build();
        uploadManager = new UploadManager(config);
        geocoderSearch = new GeocodeSearch(mContext);
    }

    @Override
    public void initView() {
        if (type == AppConstant.STATE_ADD_SHOP) {
            ctb.setTvTitle("新建门店");
        } else if (type == AppConstant.STATE_EDIT_SHOP) {
            ctb.setTvTitle("编辑门店");
        }

        ctb.setLeftImageSrc(R.drawable.iv_back);
        mapContainer.setScrollView(scrollView);
        initListener();
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    private void initListener() {
        geocoderSearch.setOnGeocodeSearchListener(this);
    }

    @Override
    public String getPageTag() {
        return FragmentAddEditShop.class.getName();
    }

    @OnClick(R.id.layout_shop_addr)
    void shopAddrClick() {
        KeyboardUtils.hideSoftInput(_mActivity);
        if (isLoaded) {
            showPickerView();
        } else {
            Toast.makeText(mContext, "数据暂未解析成功，请等待", Toast.LENGTH_SHORT).show();
        }
    }

    @OnClick(R.id.btn_add_shop)
    void addShop() {
        sendRequestAddShop();
    }

    @OnClick(R.id.iv_add_pic)
    void addPic() {
        SelectPicUtil.showDialogSelectPic("上传门店logo", mOnSelectPhotoListener, this);
    }

    @OnClick(R.id.iv_delete_pic)
    void deletePic() {
        hideShopLogo();
        picUrl = null;
    }

    @OnClick(R.id.iv_addr_search)
    void searchAddress() {
        String address = etExactAddr.getText().toString();
        if (!TextUtils.isEmpty(address)) {
            searchAddress(address);
        } else {
            ToastUtils.showShort("请输入地址再搜索");
        }
    }

    @OnClick(R.id.image_left)
    void popClick() {
        pop();
    }


    private void showShopLogo(String url) {
        layoutDeletePic.setVisibility(View.VISIBLE);
        ImageLoaderUtils.display(mContext, ivShopLogo, url);
    }

    private void hideShopLogo() {
        layoutDeletePic.setVisibility(View.GONE);
    }

    private void bindDetail(StoreDetailBean storeDetailBean) {
        etPostalCode.setText(storeDetailBean.getPostCode());
        etExactAddr.setText(storeDetailBean.getConnectAddress());
        etLoginName.setText(storeDetailBean.getUserName());
        etLoginPwd.setText(AppConstant.DEFAULT_PWD);
        etShopName.setText(storeDetailBean.getStoreName());
        etShopPhoneNum.setText(storeDetailBean.getMobileNum());
        showShopLogo(storeDetailBean.getStoreLogoUrl());
        picUrl = storeDetailBean.getStoreLogoUrl();
        String districtStr = "";
        if (!TextUtils.isEmpty(storeDetailBean.getCity())) {
            districtStr = storeDetailBean.getProvince() + "," + storeDetailBean.getCity() + "," + storeDetailBean.getDistrict();
            tvShopAddr.setText(districtStr);
        } else {
            districtStr = storeDetailBean.getProvince() + "," + storeDetailBean.getCity();
            tvShopAddr.setText(districtStr);
        }
        GeocodeQuery query = new GeocodeQuery(storeDetailBean.getConnectAddress(), storeDetailBean.getCity());// 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode，
        geocoderSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求
    }

    private void searchAddress(String addr) {
        String searchCity = defaultCity;
        if (!TextUtils.isEmpty(city)) {
            searchCity = city;
        }
        GeocodeQuery query = new GeocodeQuery(addr, searchCity);// 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode，
        geocoderSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求
    }

    private void sendRequestGetStoreById(int id) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    storeDetailBean = (StoreDetailBean) JsonUtil.getObject(response.getReturnContent(), StoreDetailBean.class);
                    bindDetail(storeDetailBean);
                }
            }
        };
        ApiMethodBoss.getStoreById(new SimpleLbObserver(listener, otherListener), id, this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestAddShop() {
        RequestBody body = getRequestBody();
        if (body == null) {
            return;
        }
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                    if (type == AppConstant.STATE_EDIT_SHOP) {
                        ToastUtils.showShort("编辑门店成功");
                        EventBus.getDefault().post(new EditShopEvent());
                    } else {
                        ToastUtils.showShort("新增门店成功");
                        EventBus.getDefault().post(new AddShopEvent());
                        EventBus.getDefault().post(new AddShopEventInMine());
                        EventBus.getDefault().post(new RookieAddShopEvent());
                    }
                    pop();
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        };
        ApiMethodBoss.addShop(new SimpleLbObserver(listener, otherListener), body, this, FragmentEvent.DESTROY_VIEW);
    }


    private CameraPosition getCameraPosition() {
        return cameraPosition;
    }

    private void setCameraPosition(CameraPosition cameraPosition) {
        this.cameraPosition = cameraPosition;
    }

    private RequestBody getRequestBody() {
        //必填
        String shopName = etShopName.getText().toString();
        if (TextUtils.isEmpty(shopName)) {
            ToastUtils.showShort("门店名称必填");
            return null;
        }
        String shopPhoneNum = etShopPhoneNum.getText().toString();
        if (TextUtils.isEmpty(shopPhoneNum)) {
            ToastUtils.showShort("联系电话必填");
            return null;
        }
        String postalCode = etPostalCode.getText().toString();
        if (TextUtils.isEmpty(postalCode)) {
            ToastUtils.showShort("邮政编码必填");
            return null;
        }
        if (TextUtils.isEmpty(picUrl)) {
            ToastUtils.showShort("门店logo必须选择");
            return null;
        }
        String shopDetailAddr = etExactAddr.getText().toString();
        if (TextUtils.isEmpty(shopDetailAddr)) {
            ToastUtils.showShort("详细地址必填");
            return null;
        }
        String loginName = etLoginName.getText().toString();
        if (TextUtils.isEmpty(loginName)) {
            ToastUtils.showShort("登录账户必填");
            return null;
        }
        String loginPwd = etLoginPwd.getText().toString();
        if (TextUtils.isEmpty(loginPwd)) {
            ToastUtils.showShort("登录密码必填");
            return null;
        }
        HashMap hashMap = new HashMap();
        if (type == AppConstant.STATE_EDIT_SHOP) {
            hashMap.put("storeCode", storeDetailBean.getStoreCode());
            hashMap.put("id", storeDetailBean.getId());
        } else {
            hashMap.put("id", 0);
        }
        hashMap.put("storeName", shopName);
        hashMap.put("mobileNum", shopPhoneNum);
        hashMap.put("postCode", postalCode);
        hashMap.put("storeLogoUrl", picUrl);
        hashMap.put("userName", loginName);
        if (!loginPwd.equals(AppConstant.DEFAULT_PWD)) {
            if (!loginPwd.contains("……")) {
                hashMap.put("userPwd", loginPwd);
            }
        }
        hashMap.put("connectAddress", shopDetailAddr);
        hashMap.put("province", province);
        hashMap.put("city", city);
        hashMap.put("district", district);
        return BizUtil.getBodyFromMap(hashMap);
    }

    private void showPickerView() {// 弹出选择器
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                province = options1Items.get(options1);
                city = options2Items.get(options1).get(options2);
                district = options3Items.get(options1).get(options2).get(options3);
                String districtStr = province + "," + city + "," + district;
                tvShopAddr.setText(districtStr);
            }
        }).setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        if (options2Items.get(0).size() != 0) {
            pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
            pvOptions.show();
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
//                        Toast.makeText(mContext, "开始解析数据", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
//                    Toast.makeText(mContext, "解析数据成功", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
//                    Toast.makeText(mContext, "解析数据失败", Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };

    private void initJsonData() {//解析数据
        ArrayList<AreaBean> jsonBean = parseData(mUserConfigManager.getDistrictInfo());//用Gson 转成实体
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            options1Items.add(jsonBean.get(i).getName());
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getChild().size(); c++) {//遍历该省份的所有城市
                AreaBean CityName = jsonBean.get(i).getChild().get(c);
                cityList.add(CityName.getName());//添加城市

                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getChild().get(c).getChild() == null
                        || jsonBean.get(i).getChild().get(c).getChild().size() == 0) {
                    city_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getChild().get(c).getChild().size(); d++) {//该城市对应地区所有数据
                        AreaBean areaDis = jsonBean.get(i).getChild().get(c).getChild().get(d);

                        city_AreaList.add(areaDis.getName());//添加该城市所有地区数据
                    }
                }
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<AreaBean> parseData(String result) {//Gson 解析
        ArrayList<AreaBean> listPro = new ArrayList<>();
        try {
            JSONArray jsonProvinces = new JSONArray(result);
            for (int i = 0; i < jsonProvinces.length(); i++) {
                AreaBean areaPro = new AreaBean();
                JSONObject jsonPro = (JSONObject) jsonProvinces.get(i);
                String province = jsonPro.getString("v");
                areaPro.setName(province);
                if (jsonPro.has("c")) {
                    ArrayList<AreaBean> listCity = new ArrayList<>();
                    JSONArray jsonCitys = jsonPro.getJSONArray("c");
                    for (int j = 0; j < jsonCitys.length(); j++) {
                        AreaBean areaCity = new AreaBean();
                        JSONObject jsonCity = (JSONObject) jsonCitys.get(j);
                        areaCity.setName(jsonCity.getString("v"));
                        if (jsonCity.has("c")) {
                            ArrayList<AreaBean> listDis = new ArrayList<>();
                            JSONArray jsonDiss = jsonCity.getJSONArray("c");
                            for (int k = 0; k < jsonDiss.length(); k++) {
                                JSONObject jsonDis = (JSONObject) jsonDiss.get(k);
                                AreaBean areaDis = new AreaBean();
                                areaDis.setName(jsonDis.getString("v"));
                                listDis.add(areaDis);
                            }
                            areaCity.setChild(listDis);
                        }
                        listCity.add(areaCity);
                    }
                    areaPro.setChild(listCity);
                }
                listPro.add(areaPro);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return listPro;
    }


    private DialogSelectPic.OnSelectPhotoListener mOnSelectPhotoListener = new DialogSelectPic.OnSelectPhotoListener() {
        @Override
        public void onTakePhoto(int id, boolean ifCrop) {
            File file = new File(AppConfigManager.DIR_IMAGE + System.currentTimeMillis() + AppConstant.JPG); // 存放路径
            if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
            Uri imageUri = Uri.fromFile(file);

            configCompress(takePhoto);
            configTakePhotoOption(takePhoto);
            switch (id) {
                case R.id.rl_profile_take_photo:
                    takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions());
                    break;
                case R.id.rl_profile_local_photo:
                    takePhoto.onPickFromGalleryWithCrop(imageUri, getCropOptions());
                    break;
            }
        }
    };

    private void sendRequestGetQiniuToken() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    QiniuInfo qiniuInfo = (QiniuInfo) JsonUtil.getObject(response.getReturnContent(), QiniuInfo.class);
                    String token = qiniuInfo.getUploadToken();
                    final String domain = qiniuInfo.getPathUrl();//http://static.storeer.com/appuser/headpic/
                    String key = AppConstant.QINIU_PATH + System.currentTimeMillis() + "_android_" + BizUtil.getRandomName(3) + AppConstant.PNG;
                    uploadManager.put(filePath, key, token, new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject response) {
                            try {
                                picUrl = domain + "/" + response.getString("key");
                                showShopLogo(picUrl);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, null);
                } else {
                    ToastUtils.showShort("暂时不能上传门店logo");
                }
            }
        };
        ApiMethodGuide.getQiniuToken(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

    private CropOptions getCropOptions() {
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(1).setOutputY(1);
        builder.setWithOwnCrop(true);
        return builder.create();
    }

    private void configCompress(TakePhoto takePhoto) {
        int height = 480;
        int width = 480;
        int maxSize = 204800;
        LubanOptions option = new LubanOptions.Builder()
                .setMaxHeight(height)
                .setMaxWidth(width)
                .setMaxSize(maxSize)
                .create();
        CompressConfig config = CompressConfig.ofLuban(option);
        config.enableReserveRaw(true);
        takePhoto.onEnableCompress(config, true);
    }

    private void configTakePhotoOption(TakePhoto takePhoto) {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true);
        builder.setCorrectImage(true);
        takePhoto.setTakePhotoOptions(builder.create());
    }


    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
//        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onDestroy() {
        if (aMap != null) {
            setCameraPosition(aMap.getCameraPosition());
        }
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void takeSuccess(TResult result) {
        filePath = result.getImage().getCompressPath();
        if (!TextUtils.isEmpty(filePath)) {
            sendRequestGetQiniuToken();
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
    }

    @Override
    public void takeCancel() {
        ToastUtils.showShort("取消");
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

    }

    @Override
    public void onGeocodeSearched(GeocodeResult result, int code) {
        if (code == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getGeocodeAddressList() != null
                    && result.getGeocodeAddressList().size() > 0) {
                GeocodeAddress address = result.getGeocodeAddressList().get(0);
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(AMapUtil.convertToLatLng(address.getLatLonPoint()), 15));
                shopMarker.setPosition(AMapUtil.convertToLatLng(address
                        .getLatLonPoint()));
//                addressName = "经纬度值:" + address.getLatLonPoint() + "\n位置描述:"
//                        + address.getFormatAddress();
//                ToastUtil.show(GeocoderActivity.this, addressName);
            } else {
                ToastUtils.showShort("搜索不到该地址");
//                ToastUtil.show(GeocoderActivity.this, R.string.no_result);
            }
        } else {
//            ToastUtil.showerror(this, code);
        }
    }
}
